package com.chilly.other.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * Semaphore 的计数器是递增的
 * 构造函数传入的初始值为0，当子线程调用release()方法时，计数器递增，
 * 主线程acquire()传参为3 则说明主线程一直阻塞，直到计数器为3才会返回。
 *
 * <p>
 * Created by Chilly Cui on 2020/12/11.
 */
public class SemaphoreDemoMeeting {
    private static int num = 3;

    private static int initNum = 0;
    private static Semaphore semaphore = new Semaphore(initNum);

    private static ExecutorService executorService = Executors.newFixedThreadPool(num);

    public static void main(String[] args) throws InterruptedException {
        executorService.submit(() -> {
            System.out.println("A在上厕所");
            try {
                Thread.sleep(4000);
                semaphore.release();
                System.out.println("A上完了");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {

            }
        });
        executorService.submit(() -> {
            System.out.println("B在上厕所");
            try {
                Thread.sleep(2000);
                semaphore.release();
                System.out.println("B上完了");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {

            }
        });
        executorService.submit(() -> {
            System.out.println("C在上厕所");
            try {
                Thread.sleep(3000);
                semaphore.release();
                System.out.println("C上完了");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {

            }
        });

        System.out.println("等待所有人从厕所回来开会...");
        semaphore.acquire(num); //主线程一直阻塞，直到计数器为3才会返回。
        System.out.println("所有人都好了，开始开会...");

        executorService.shutdown();
    }

}
